R graphs

Explore and analize data visually

Dr. Peng Zhao (✉ peng.zhao@xjtlu.edu.cn)

Department of Health and Environmental Sciences
Xi’an Jiaotong-Liverpool University

1 Prerequisites

  1. Basic Knowledge in R.
  2. Installation of R and RStudio IDE (instructions in English and in Chinese
  3. Packages

2 Objectives

  1. Know what graphs R could produce
  2. Get familiar with four popular R packages for graphing, including basic packages, ggplot2, plotly, and rgl, and the ways to produce them, including coding and GUI.
  3. Be able to Plot common graphs with R.

3 What R can plot

3.1 Traditional

:width 80%

:width 100%

3.2 Interactive

3.3 Animated

3.4 Geographical

3.5 Amazing

3.6 Ubiquitous

4 Graph components

  • Graph area

    • Plotting area
    • Axes
    • Legends
  • Figure number + caption (not required in this module)

5 Packages

5.1 Basic R

Function Usage
plot()
pairs()
symbols()
hist()
curve()
barplot()
boxplot()
coplot()
dotchart()
stripchart()
image()
contour()
lines()
points()
abline()
axis()
legend()
text()
mtext()
layout()

5.2 ggplot2

ggplot() +      # mandatory: data mapping
  geom_xxx() +  # mandatory: geometry shape
  coordinate_xxx() +  
  theme() +          
  facet_xxx() +      
  ...
Function Usage
geom_point() scatter plot
geom_line()
geom_bar()
geom_histogram()
geom_freqpoly()
geom_density()
geom_boxplot()
geom_bin2d()
geom_density2d()
geom_contour()
geom_abline()
geom_text()
geom_errorbar()
geom_polygon()
geom_rect()
geom_smooth()

6 Graphical User Interface

library(GrapheR)
run.GrapheR()
library(Rcmdr)
ggplotgui::ggplot_shiny()
library(Deducer)
JGR()

7 Exercises

  1. Make a box plot for iris$Sepal.Lengthwith ggplot2 and basic R.
  2. What are the differences between plotting graphs with R and with Excel? Compare the pros and cons.
  3. What can the interactive plotly images be used for?
  4. What pros and cons do 3D images (made by rgl , for example) have?

8 Further readings

9 Demos

# Packages ----------------------------------------------------------------
install.packages(c('beginr', 'ggplot2','plotly', 'GGally', 'remotes', 'MSG', 'fun','rayshader', 'animation'))
remotes::install_github('pzhaonet/fecitr')

# Data ----------------------------------------------------------
data(airquality)
airquality$Month <- as.factor(airquality$Month)

# Basic R -----------------------------------------------------------------
boxplot(airquality$Temp)
boxplot(airquality$Temp ~ airquality$Month, 
        xlab = 'Month', 
        ylab = 'Temperature',
        las = 1,
        col = c('red', 'yellow', 'green', 'blue', 'purple'))

plot(airquality$Solar.R, airquality$Temp)
plot(airquality$Solar.R, airquality$Temp,
     xlab = 'Solar Radiation',
     ylab = 'Temperature',
     pch = 16, 
     las = 1,
     col = airquality$Month)
abline(lm(airquality$Temp ~ airquality$Solar.R))
legend(0, 95, legend = 5:9, col = 5:9, pch = 16)

# Previously from Dr. Yi Zou for derivation
f <- expression(x ^ 2 + 5 * x + 1)
D(f, "x") 
curve(x ^ 2 + 5 * x + 1, xlim = c(-5, 5), col = 'blue')
curve(2 * x + 5, col = 'red', add = TRUE)

# fecitr
library(fecitr)
plot_summary(airquality)
plot_summary(airquality, 
             if_box = TRUE, 
             base = "hist")

# more
demo('graphics')
demo('persp')

# ggplot2 -----------------------------------------------------------------
library(ggplot2)
ggplot(airquality) +
  geom_boxplot(aes(Temp))
p1 <- ggplot(airquality) +
  geom_boxplot(aes(Month, Temp, fill = Month))
p1

p2 <- ggplot(airquality) + 
  geom_point(aes(Solar.R, Temp, color = Month))
p2

p3 <- p2 + geom_smooth(aes(Solar.R, Temp), method = 'lm')
p3 + geom_smooth(aes(Solar.R, Temp, color = Month), method = 'lm')
p3 + facet_wrap(Month ~.) + theme_dark()

p4 <- ggplot(airquality) +
  geom_bin_2d(aes(Solar.R, Temp))
p4

# GGally
library(GGally)
p5 <- ggpairs(airquality, 
              aes(fill = Month, alpha = 0.1))
p5

# rayshader
library(rayshader)
plot_gg(p4)

# more
example(qplot, "ggplot2")

# plotly --------------------------------------------------------
library(plotly)
plot_ly(x = iris$Sepal.Length, y = iris$Sepal.Width)
ggplotly(p1)
ggplotly(p3)
ggplotly(p4)
ggplotly(p5)

# more
demo('crosstalk-highlight-binned-target-a', package = 'plotly')

# rgl ---------------------------------------------------------------------
library(rgl)
heart <- readRDS(url('https://pzhao.org/data/heart.RDS'))
persp3d(heart$z, heart$x, heart$y, col = "red")
demo("ChinaHeart3D", package = "fun")

# more
for (i in 1:10) demo(demo(package = 'rgl')$results[i, 3], character.only = TRUE)

# My book -----------------------------------------------------------
library(MSG)
Sys.setlocale("LC_CTYPE", "Chinese")
msg("3.11")
# more: https://msg2020.pzhao.org/code/

# Export -----------------------------------------------------------
# In RStudio, click Plots - Export - Save as PDF. Or
# Use functions:
pdf('df_plot.pdf')
plot(iris$Sepal.Length)
dev.off()

ggpairs(iris, aes(colour=Species, alpha=0.5))
ggsave("df_ggpairs.pdf")